<?php

namespace app\admin\controller;

use app\helpers\Common;
use app\common\model\AdminRole;
use app\common\model\AdminRoleUser;

use support\Request;
use support\View;
use think\facade\Db;
use think\Exception;

class AdminController extends BaseController
{

    protected $fields = []; // Form 表单展示的字段

    protected function initialize()
    {
        parent::initialize();

//        $this->fields = [
//            'id', 'status', 'username', 'password', 'nickname', 'email', 'sex', 'lang', 'auto_logout', 'last_login_time', 'last_login_ip', 'avatar', 'remark'
//        ];

        $request = request();
        if ($request->action == 'add' || $request->action == 'edit') {
            // 角色
            $adminRoles = AdminRole::where(['status' => 1])->field('id, name')->select()->toArray();
            View::assign('adminRoles', $adminRoles);
        }
    }

    /**
     * Edit
     */
    public function edit(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;
        $id = $request->input('id');
        $info = $model->find($id);
        if (!$info) {
            return redirect(url('/' . $this->model . '/index'));
        }

        // 角色
        $info['role_ids'] = AdminRoleUser::where('admin_id', $info['id'])->column('role_id');

        return view(strtolower($this->model) . '/' .  $this->editView, [
            'primaryKey' => $this->primaryKey,
            'info' => $info
        ]);
    }

    /**
     * Save Post
     */
    protected function savePost($request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        if ($request->post()) {
            Db::startTrans();
            try {
                $data = self::evalData($request);
                if (isset($data['password']) && !empty($data['password'])) {
                    $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
                }
                $roleIds = $data['role_ids'];
                unset($data['confirm_password']);
                unset($data['role_ids']);

                if ($data['id']) {
                    // Update data
                    $data['updated_at'] = time();
                    $data['updated_id'] = $this->admin['id'];
                    $result = $model->where('id', $data['id'])->save($data);

                    $logInfo = $this->admin['name'] . '更新了一条' . __($this->model) . '数据。';
                    $afterAction = '_after_update';
                } else {
                    // Insert data
                    $data['created_at'] = time();
                    $data['created_id'] = $data['updated_id'] = $this->admin['id'];
                    $result = $model->create($data);

                    $logInfo = $this->admin['name'] . '添加了一条' . __($this->model) . '数据。';
                    $afterAction = '_after_insert';
                }

                if ($result !== false) {
                    if (!$data['id']) {
                        $data['id'] = $result->id;
                    }
                    AdminRoleUser::where('admin_id', $data['id'])->delete();
                    foreach ($roleIds as $roleId) {
                        $res = AdminRoleUser::insert(['role_id' => $roleId, 'admin_id' => $data['id']]);
                        if ($res === false) {
                            Db::rollback();
                            return $this->error('保存管理员角色失败!', url('/' . $this->model . '/index'));
                        }
                    }

                    // Query执行后的操作
                    $model->$afterAction($data);

                    // 写入日志
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('保存成功！', url('/' . $this->model . '/index'));
                } else {
                    Db::rollback();
                    return $this->error('保存失败!', url('/' . $this->model . '/index'));
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
        } else {
            return $this->error('请求方式错误!');
        }
    }

    /**
     * Delete
     */
    public function delete(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        $id = $request->input('id');
        $primaryKey = $this->primaryKey;
        if (isset($_POST['ids'])) {
            // 删除多条
            $ids = $request->input('ids');
            $result = $model->whereIn($primaryKey, $ids)->update(['status' => 90, 'deleted_id' => $this->admin['id'], 'deleted_at' => time()]);
        } else if ($id) {
            // 删除一条
            $info = $model->find($id);
            if (!$info) {
                return $this->error('数据不存在!');
            }
            $result = $model->where($primaryKey, $id)->update(['status' => 90, 'deleted_id' => $this->admin['id'], 'deleted_at' => time()]);
        }

        if ($result !== false) {
            // 写入日志
            $logInfo = $this->admin['name'] . '删除了一条' . __($this->model) . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('删除成功!', url('/' . $this->model . '/index'));
        } else {
            return $this->error('删除失败!', url('/' . $this->model . '/index'));
        }
    }

    /**
     * Info
     */
    public function info(Request $request)
    {
        return view('', [
            'primaryKey' => $this->primaryKey,
        ]);
    }

    /**
     * Profile
     */
    public function profile(Request $request)
    {
        return view(strtolower($this->model) . '/' . 'profile', [
            'primaryKey' => $this->primaryKey,
        ]);
    }

    public function infoPost(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        if ($request->isAjax()) {
            $data = $request->all();

            $adminInfo = $model->where('id', $this->admin['id'])->find();
            if ($adminInfo) {
                $adminInfo->username = $data['username'];
                $adminInfo->email = $data['email'];
                $adminInfo->avatar = $data['avatar'];

                $result = $adminInfo->save();
                if ($result !== false) {
                    $adminInfo['full_avatar'] = full_file_url($data['avatar']);
                    $adminInfo = json_decode(json_encode($adminInfo), true);
                    session(['admin' => $adminInfo]);

                    // 写入日志
                    $logInfo = $this->admin['name'] . '更新了一次个人数据。';
                    Common::adminLog($request, $logInfo);

                    return $this->success('保存成功!', url('/' . $this->model . '/index'));
                } else {
                    return $this->error('保存失败!', url('/' . $this->model . '/index'));
                }
            } else {
                return $this->error('此用户不存在!', url('/' . $this->model . '/index'));
            }
        }
    }

    /**
     * 修改密码
     */
    public function resetPassword(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        if ($request->isAjax()) {
            $param = $request->all();

            $password = trim($param['password']);
            $newPassword = trim($param['newpassword']);
            $confirmPassword = trim($param['confirmpassword']);

            if (!$password) {
                return $this->error('原始密码不能为空!', url('/' . $this->model . '/index'));
            }
            if (!$newPassword) {
                return $this->error('新密码不能为空!', url('/' . $this->model . '/index'));
            }
            if ($newPassword != $confirmPassword) {
                return $this->error('两次密码不一致!', url('/' . $this->model . '/index'));
            }

            $admin = $model->where('id', $this->admin['id'])->find();
            if ($admin) {
                if (!password_verify($password, $admin['password'])) {
                    return $this->error('此用户不存在!', url('/' . $this->model . '/index'));
                    return json(['code' => 0, 'msg' => '原密码不正确！']);
                } else {
                    $data['password'] = password_hash($newPassword, PASSWORD_BCRYPT);
                    $result = $model->where('id', $this->admin['id'])->update($data);

                    if ($result !== false) {
                        // 写入日志
                        $logInfo = $this->admin['name'] . '修改了一次个人密码。';
                        Common::adminLog($request, $logInfo);

                        return $this->success('保存成功!', url('/' . $this->model . '/index'));
                    } else {
                        return $this->error('保存失败!', url('/' . $this->model . '/index'));
                    }
                }
            } else {
                return $this->error('此用户不存在!', url('/' . $this->model . '/index'));
            }
        }

        return view(strtolower($this->model) . '/' . 'reset_password');
    }

    /**
     * 检查登录名是否已存在
     */
    public function checkLoginName(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        $loginName = $request->input('username');
        $where = [
            ['username', '=', $loginName],
            ['status', '=', 1]
        ];
        $info = $model->where($where)->field('id')->find();

        if ($info) {
            return json(['code' => 1]);
        } else {
            return json(['code' => 0]);
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        $data = $model->formatDatas($data);
//        foreach ($data as $item) {
//            $item = $model->formatItem($item);
//        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }
        if (isset($param['email']) && $param['email']) {
            $where[] = ['email', 'like', '%' . trim($param['email']) . '%'];
        }

        return $where;
    }
}